package bootstrap

import (
	"com.codingq92/go-chat/global"
	"com.codingq92/go-chat/middleware"
	"com.codingq92/go-chat/routes"
	"com.codingq92/go-chat/services"
	"context"
	"errors"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

// RunServer 启动服务
func RunServer() {
	g := setupRouter()
	ser := &http.Server{
		Addr:    ":" + global.Config.App.Port,
		Handler: g,
	}
	go func() {
		if err := ser.ListenAndServe(); nil != err && !errors.Is(err, http.ErrServerClosed) {
			log.Fatalf("Server run failed: %s\n", err)
		}
	}()
	//等待信号中断优雅关闭服务()
	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	log.Println("Shutdown Server ...")
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := ser.Shutdown(ctx); nil != err {
		log.Fatal("Server Shutdown: ", err)
	}
	log.Println("Server exiting")
}

func setupRouter() *gin.Engine {
	g := gin.Default()

	//前端项目静态资源
	g.StaticFile("/", "./static/dist/index.html")
	g.Static("/assets", "./static/dist/assets")
	//g.StaticFile("/favicon.ico", "./static/dist/favicon.ico")
	g.StaticFile("/vite.svg", "./static/dist/vite.svg")
	//其他静态资源
	g.Static("/public", "./static")
	g.Static("/storage", "./storage/app/public")

	//测试接口
	testGroup := g.Group("/test")
	routes.SetTestGroupRoutes(testGroup)
	//登录/注册相关
	sysGroup := g.Group("/sys")
	routes.SetSysApiGroupRoutes(sysGroup)
	//系统级别接口
	authApiGroup := g.Group("/api")
	authApiGroup.Use(middleware.JWTAuth(services.AppGuardName))
	routes.SetApiGroupRoutes(authApiGroup)
	return g
}
